<template>
  <FormDrawer ref="formDrawerRef" title="推荐商品" @submit="handleConnect" @cancel="handleCancel" confirmText="关联">
    <el-table :data="tableData" border stripe style="width: 100%;">
      <el-table-column prop="goods_id" label="id" width="60" />
      <el-table-column label="商品封面" width="180">
        <template #default="{ row }">
          <el-image :src="row.cover" fit="fill" :lazy="true" style="width:64px; height: 64px"/>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" width="180" />
      <el-table-column label="操作" width="60">
        <template #default="{ row }">
          <el-popconfirm
            title="是否删除该推荐商品"
            confirmButtonText="确定"
            cancelButtonText="取消"
            @confirm="handleDelete(row)"
          >
            <template #reference>
              <el-button type="primary" text size="small" :loading="row.loading">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </FormDrawer>

  <ChooseGoods ref="chooseGoodsRef"/>
</template>

<script setup>
  import { ref } from 'vue'
  import FormDrawer from '@/components/FormDrawer.vue'
  import { getCategoryGoodsApi, deleteCategoryGoodsApi, connectCategoryGoodsApi } from '@/api/category.js'
  import ChooseGoods from '@/components/ChooseGoods.vue'
  import { toast } from '@/utils'

  const formDrawerRef = ref(null)
  const category_id = ref(0)
  const tableData = ref([])
  function open(item) {
    category_id.value = item.id
    item.goodsDrawerLoading = true
    getData()
      .then(res => formDrawerRef.value.open())
      .finally(() => item.goodsDrawerLoading = false)
  }

  function getData() {
    return getCategoryGoodsApi(category_id.value)
      .then(res => {
        tableData.value = res.map(o => {
          o.loading = false
          return o
        })
      })
  }

  function handleDelete(row) {
    row.loading = true
    deleteCategoryGoodsApi(row.id)
      .then(res => {
        toast('删除成功')
        getData()
      })
      .finally(() => row.loading = false)
  }

  function handleCancel() {
    formDrawerRef.value.close()
  }

  const chooseGoodsRef = ref(null)
  function handleConnect() {
    formDrawerRef.value.showLoading()
    chooseGoodsRef.value.open((goods_ids) => {
      connectCategoryGoodsApi({ category_id: category_id.value, goods_ids })
        .then(res => {
          toast('关联成功')
          getData()
        })
        .finally(() => formDrawerRef.value.hideLoading())
    })
  }

  defineExpose({
    open
  })
</script>

<style scoped>
</style>